package com.rw.admin.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("file")
public class FileController {

    @Value("${file.upload.path}")
    private String path;
    @Value("${img.url.base}")
    private String baseUrl;

    @RequestMapping("upload")
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("code",200);
        //图片上传的逻辑
        //获取图片的名字
        String imgName=file.getOriginalFilename();
        //获取Mime类型,验证是否为图片类型
        System.out.println("老文件名是："+imgName);
        String mimeType = request.getServletContext().getMimeType(imgName);
        if(mimeType==null || !mimeType.contains("image")){
            map.put("code",199);
            map.put("msg","文件类型错误");
            return map;
        }
        String newName = UUID.randomUUID().toString();
        String[] names = imgName.split("\\.");
        for (String item:names) {
            System.out.println(item);
        }

        String surfix = names[names.length - 1];
        newName = newName+"."+surfix;

        String newFilePath = path+newName;
        System.out.println("新文件名是："+newName);

        //保存到服务器的文件名
        File dest = new File(newFilePath);
        //保存文件
        try {
            Files.copy(file.getInputStream(), dest.toPath());
            map.put("filePath",newFilePath);
            //拼接图片访问地址
            String imgUrl = baseUrl+newName;
//            map.put("imgUrl",imgUrl);
            map.put("msg","文件上传成功");
            map.put("name",newName);
            map.put("baseUrl",baseUrl);
        }catch (IOException e) {
            map.put("code",100);
            map.put("msg","文件上传异常"+e.getMessage());
        }
        return map;

    }

    public static void main(String[] args) {
        String name = "1.jpeg";
        String[] names = name.split(".");
        for (String item:names) {
            System.out.println(item);
        }
    }
}
